<template>
  <div class="ai-editor">
    <el-button @click="addComment" type="warning">添加批注</el-button>
    <el-button type="primary" size="small" @click="saveJSON">保存 JSON</el-button>
    <el-button type="primary" size="small" @click="saveHTML">保存 HTML</el-button>
    <el-button type="primary" size="small" @click="saveText">保存 TXT</el-button>
    <el-button type="primary" size="small" @click="savePdf">保存 PDF</el-button>
    <editor-content :editor="editor" class="editor" />
  </div>
</template>

<script setup lang="ts">
import { useEditor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { ExtendedImage } from '@/tiptap/extensions/ExtendedImage'
import { SaveContentExtension } from '@/tiptap/extensions/SaveContentExtension'
import { Plugin, PluginKey } from 'prosemirror-state'
import { ShortcutCopyPlugin } from '@/tiptap/extensions/ShortcutCopyPlugin'
//请求后端保存图片到本地
const uploadImage = async (file: File): Promise<string> => {
  const formData = new FormData()
  formData.append('file', file)

  const response = await fetch('http://localhost:8080/api/upload/image', {
    method: 'POST',
    body: formData,
  })

  if (!response.ok) {
    throw new Error('上传失败')
  }

  const result = await response.json()
  return result.url // 返回后端生成的图片 URL
}


// 图片粘贴处理插件
const editor = useEditor({
  extensions: [StarterKit, ExtendedImage, SaveContentExtension],
  content: '请粘贴图片测试',
editorProps: {
handlePaste(view, event) {
  const items = Array.from(event.clipboardData?.items || [])
  for (const item of items) {
    if (item.type.indexOf('image') === 0) {
      const file = item.getAsFile()
      if (!file) return false

      const sizeMB = file.size / 1024 / 1024
      if (sizeMB > 10) {
        alert('图片必须小于 10MB')
        return true
      }

      // ✅ 先上传再插入
      uploadImage(file)
        .then((realPath) => {
          const finalUrl = realPath.startsWith('http')
            ? realPath
            : `http://localhost:8080/api${realPath}`

          const { schema, tr } = view.state
          const imageNode = schema.nodes.image.create({
            src: finalUrl,
            draggable: true
          })

          const insertPos = tr.selection.from
          view.dispatch(tr.insert(insertPos, imageNode))
        })
        .catch((err) => {
          console.error('图片上传失败', err)
          alert('图片上传失败，请检查文件格式或网络')
        })

      return true
    }
  }
  return false
},

},
onCreate({ editor }) {
  editor.registerPlugin(ShortcutCopyPlugin(editor))
}

})



// 保存操作函数
const saveJSON = () => editor.value?.commands.saveJSON()
const saveHTML = () => editor.value?.commands.saveHTML()
const saveText = () => editor.value?.commands.saveText()
const savePdf = () => editor.value?.commands.savePdf()

// 添加批注功能（示例）
const addComment = () => {
  alert('批注功能待实现')
}
</script>

<style scoped>
.editor {
  border: 1px solid #ccc;
  padding: 12px;
  min-height: 200px;
  margin-top: 12px;
}

::v-deep(.tiptap-comment) {
  background-color: rgba(255, 200, 0, 0.4);
  border-bottom: 1px dashed orange;
}
::v-deep(.ProseMirror img) {
  user-select: all;
  pointer-events: auto;
  max-width: 100%;
}
::v-deep(.ProseMirror img.selected-image) {
  outline: 2px solid #409EFF;
}
</style>
